package com.slipper.system.log.service;

import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.util.DateUtil;
import com.slipper.util.UUID;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.log.dao.LoginLogDao;
import com.slipper.system.log.bo.LoginLogBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;

@Service
@ReadTransactional
public class LoginLogService {
    @Resource
    private LoginLogDao loginLogDao;
    
    public LoginLogBO queryBy(String id) {
        return loginLogDao.queryBy(id);
    }
    
    public List<LoginLogBO> queryList(LoginLogBO bo) {
        return loginLogDao.queryList(bo);
    }
    
    public PageInfo<LoginLogBO> queryPage(LoginLogBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(loginLogDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(LoginLogBO bo) {
        bo.setId(UUID.getUUID());
        bo.setCreateTime(System.currentTimeMillis());
        return loginLogDao.insert(bo);
    }
    
    @WriteTransactional
    public int delete(LoginLogBO bo) {
        return loginLogDao.delete(bo);
    }

    public List<Map<String, Object>> queryMonthStatList() {
        List<Map<String, Object>> resultList = new ArrayList<>();

        LoginLogBO bo = new LoginLogBO();
        bo.setStartDate(DateUtil.getNextMonth(new Date(), -1));

        List<LoginLogBO> logList = loginLogDao.queryList(bo);
        logList.stream()
                .collect(Collectors.groupingBy(item -> DateUtil.formatDate(item.getCreateTime())))
                .forEach((key, value) -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("loginDate", key);
                    result.put("loginMans", value.stream().map(LoginLogBO::getUserId).distinct().count());
                    result.put("loginTimes", value.size());
                    resultList.add(result);
                });
        resultList.sort(Comparator.comparing(a -> a.get("loginDate").toString()));
        return resultList;
    }
}
